package com.ruoyi.web.controller.store.pan;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.StorePan;
import com.ruoyi.common.core.domain.entity.StorePanDetail;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.mapper.RestaurantStoreResourceMapper;
import com.ruoyi.system.mapper.StorePanMapper;
import com.ruoyi.system.service.IStorePanDetailService;
import com.ruoyi.system.service.IStorePanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 盘点明细Controller
 *
 * @author wlmes
 * @date 2023-11-23
 */
@RestController
@RequestMapping("/system/detail")
@Api(tags = "盘点明细相关接口")
public class StorePanDetailController extends BaseController {
    @Autowired
    private IStorePanDetailService storePanDetailService;
    @Autowired
    private StorePanMapper storePanMapper;
    @Resource
    IStorePanService storePanService;
    @Resource
    RestaurantStoreResourceMapper storeResourceMapper;

    /**
     * 查询盘点明细列表
     */
    @GetMapping("/list")
    @ApiOperation("查询盘点明细列表")
    public TableDataInfo list(StorePanDetail storePanDetail) {
        startPage();
        List<StorePanDetail> list = storePanDetailService.selectStorePanDetailList(storePanDetail);
        for (StorePanDetail overflowReportDetail : list) {
            String name = storeResourceMapper.getName(overflowReportDetail.getResourceId());
            overflowReportDetail.setName(name);
            overflowReportDetail.setResourceName(name);
        }
        return getDataTable(list);
    }

    /**
     * 导出盘点明细列表
     */
//    @PreAuthorize("@ss.hasPermi('system:detail:export')")
    @Log(title = "盘点明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出盘点明细列表")
    public void export(HttpServletResponse response, StorePanDetail storePanDetail) {
        List<StorePanDetail> list = storePanDetailService.selectStorePanDetailList(storePanDetail);
        for (StorePanDetail overflowReportDetail : list) {
            String name = storeResourceMapper.getName(overflowReportDetail.getResourceId());
            overflowReportDetail.setName(name);
            overflowReportDetail.setResourceName(name);
            String unit = storeResourceMapper.getUnit(overflowReportDetail.getResourceId());
            overflowReportDetail.setUnit(unit);
        }
        ExcelUtil<StorePanDetail> util = new ExcelUtil<StorePanDetail>(StorePanDetail.class);
        util.exportExcel(response, list, "盘点明细");
    }

    /**
     * 获取盘点明细详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:detail:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取盘点明细详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(storePanDetailService.selectStorePanDetailById(id));
    }

    /**
     * 新增盘点明细
     */
//    @PreAuthorize("@ss.hasPermi('system:detail:add')")
    @Log(title = "盘点明细", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增盘点明细")
    @RepeatSubmit
    public AjaxResult add(@RequestBody StorePanDetail storePanDetail) {
//        StorePan storePan = storePanService.selectStorePanByPanNum(storePanDetail.getPanNum());
//        if (storePan == null) {
//            throw new BaseException("未找到该盘点单" + storePanDetail.getPanNum());
//        }
//        if (StringUtils.isNotBlank(storePan.getApprovalState())) {
//            if (storePan.getApprovalState().equals("1") || storePan.getApprovalState().equals("3")) {
//                throw new BaseException("该盘点单正在审核中或已通过,无法修改" + storePanDetail.getPanNum());
//            }
//        }
        return toAjax(storePanDetailService.insertStorePanDetail(storePanDetail));
    }

    /**
     * 修改盘点明细
     */
//    @PreAuthorize("@ss.hasPermi('system:detail:edit')")
    @Log(title = "盘点明细", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改盘点明细")
    @RepeatSubmit
    public AjaxResult edit(@RequestBody StorePanDetail storePanDetail) {
//        StorePan storePan = storePanService.selectStorePanByPanNum(storePanDetail.getPanNum());
//        if (storePan == null) {
//            throw new BaseException("未找到该盘点单" + storePanDetail.getPanNum());
//        }
//        if (StringUtils.isNotBlank(storePan.getApprovalState())) {
//            if (storePan.getApprovalState().equals("1") || storePan.getApprovalState().equals("3")) {
//                throw new BaseException("该盘点单正在审核中或已通过,无法修改" + storePanDetail.getPanNum());
//            }
//        }
        BigDecimal amount = storePanDetail.getRealAmount();
        storePanDetail = storePanService.getAmount(storePanDetail);
        if (amount != null) {
            storePanDetail.setRealAmount(amount);
        }
        try {
            StorePanDetail old = storePanDetailService.selectStorePanDetailById(storePanDetail.getId());
            StorePan query1 = new StorePan();
            query1.setPanNum(storePanDetail.getPanNum());
            List<StorePan> storePans = storePanMapper.selectStorePanList(query1);
            if (!CollectionUtils.isEmpty(storePans)) {
                StorePan storePan = storePans.get(0);
                BigDecimal oldMoney = (old.getPrice() == null ? BigDecimal.ZERO : old.getPrice()).multiply(old.getRealAmount() == null ? BigDecimal.ZERO : old.getRealAmount());
                storePan.setMoney(storePan.getMoney().subtract(oldMoney).add(storePanDetail.getRealAmount().multiply(storePanDetail.getPrice())));
                storePanMapper.updateStorePan(storePan);
            }
        } catch (Exception e) {

        }
        return toAjax(storePanDetailService.updateStorePanDetail(storePanDetail));
    }

    /**
     * 删除盘点明细
     */
//    @PreAuthorize("@ss.hasPermi('system:detail:remove')")
    @Log(title = "盘点明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation("删除盘点明细")
    @RepeatSubmit
    public AjaxResult remove(@PathVariable Long[] ids) {
//        for (Long id : ids) {
//            StorePanDetail storePanDetail = storePanDetailService.selectStorePanDetailById(id);
//            StorePan storePan = storePanService.selectStorePanByPanNum(storePanDetail.getPanNum());
//            if (storePan == null) {
//                throw new BaseException("未找到该盘点单" + storePanDetail.getPanNum());
//            }
//            if (StringUtils.isNotBlank(storePan.getApprovalState())) {
//                if (storePan.getApprovalState().equals("1") || storePan.getApprovalState().equals("3")) {
//                    throw new BaseException("该盘点单正在审核中或已通过,无法修改" + storePanDetail.getPanNum());
//                }
//            }
//
//        }
        for (Long id : ids) {
            try {
                StorePanDetail storePanDetail = storePanDetailService.selectStorePanDetailById(id);
                StorePan query1 = new StorePan();
                query1.setPanNum(storePanDetail.getPanNum());
                List<StorePan> storePans = storePanMapper.selectStorePanList(query1);
                if (!CollectionUtils.isEmpty(storePans)) {
                    StorePan storePan = storePans.get(0);
                    storePan.setMoney(storePan.getMoney().subtract(storePanDetail.getPrice().multiply(storePanDetail.getRealAmount())));
                    storePanMapper.updateStorePan(storePan);
                }
            } catch (Exception e) {

            }
        }

        return toAjax(storePanDetailService.deleteStorePanDetailByIds(ids));
    }
}
